package com.ww.springboot.boot.thread.study.executor;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 描述：
 * <p>
 * 1.线程池支持动态调整线程数
 * 2.线程池每个线程都是一个worker对象 worker里面保存着创建的线程
 * 3.调整会在submit时生效 调整并不会影响正在运行的线程
 * worker 里面的线程一直处于自旋状态 没有任务的时候会被中断 当线程数变化时 会触发恢复自旋 一旦判断通过 则将自己从workers中删除 线程自然也会被回收掉
 *
 * @author 🧑 ‍wanwei
 * @since 2024-01-23 17:12
 */
public class ExecutorSourceDemo5 {

    private final static ThreadPoolExecutor t = new ThreadPoolExecutor(8, 8, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

    public static void main(String[] args) throws InterruptedException {

        printInfo();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                int finalI = i;
                t.execute(() -> {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(finalI);
                });
            }
        }).start();


        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                printInfo();
            }
        }).start();

        new Thread(() -> {
            try {
                Thread.sleep(25000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            t.setCorePoolSize(2);
            t.setMaximumPoolSize(2);
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                int finalI = i;
                t.execute(() -> {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(finalI);
                });
            }
        }).start();
    }

    private static void printInfo() {
        System.out.println("核心线程数：" + t.getCorePoolSize());
        System.out.println("活跃线程数：" + t.getActiveCount());
        System.out.println("完成任务数：" + t.getCompletedTaskCount());
        System.out.println("最大线程池数：" + t.getLargestPoolSize());
        System.out.println("任务总数：" + t.getTaskCount());
        System.out.println("---------------------");
    }
}
